package userwash

import (
	"context"
	"errors"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/userwash"
	"gorm.io/gorm"
)

type UserWashBetModel struct {
	ctx context.Context
	db  *gorm.DB
}

func (m *UserWashBetModel) GetDB() *gorm.DB {
	return m.db
}

func NewUserWashBetModel(ctx context.Context, db *gorm.DB) *UserWashBetModel {
	return &UserWashBetModel{
		ctx: ctx,
		db:  db,
	}
}

// BetIncrease 投注增加
func (m *UserWashBetModel) BetIncrease(amount float64, userId int64, categoryCode, typeName string) error {
	var userWashBet userwash.UserWashBet
	tx := m.db.WithContext(m.ctx).Model(&userwash.UserWashBet{}).Where("user_id = ? and category_code = ?", userId, categoryCode)
	err := tx.First(&userWashBet).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			userWashBet = userwash.UserWashBet{
				UserId:       userId,
				TypeName:     typeName,
				CategoryCode: categoryCode,
				Value:        amount,
				TotalValue:   amount,
			}
			return m.db.WithContext(m.ctx).Create(&userWashBet).Error
		}
		return err
	}

	return tx.Updates(map[string]any{"value": gorm.Expr("value + ?", amount), "total_value": gorm.Expr("total_value + ?", amount)}).Error
}

// BetDecrease 投注减少
func (m *UserWashBetModel) BetDecrease(amount float64, userId int64, categoryCode, typeName string) error {
	tx := m.db.WithContext(m.ctx).Model(&userwash.UserWashBet{}).Where("user_id = ? and category_code = ?", userId, categoryCode)
	return tx.Updates(map[string]any{"value": gorm.Expr("value - ?", amount)}).Error
}

type Total struct {
	Value float64
}

func (m *UserWashBetModel) GetBetValue(userId int64, typeName string) (float64, error) {
	tx := m.db.WithContext(m.ctx).Model(&userwash.UserWashBet{}).Select("sum(value) as value").Where("user_id = ?", userId)
	if typeName != "" {
		tx.Where("type_name = ?", typeName)
	}
	var total Total
	return total.Value, tx.First(&total).Error
}

func (m *UserWashBetModel) GetUserWashBet(userId int64, typeName string) ([]*userwash.UserWashBet, error) {
	tx := m.db.WithContext(m.ctx).Model(&userwash.UserWashBet{}).Where("user_id = ? and value > 0", userId)
	if typeName != "" {
		tx.Where("type_name = ?", typeName)
	}
	var userWashBet []*userwash.UserWashBet
	return userWashBet, tx.Find(&userWashBet).Error
}

func (m *UserWashBetModel) BetClear(userWashBetId int64) error {
	return m.db.WithContext(m.ctx).Model(&userwash.UserWashBet{}).Where("id = ?", userWashBetId).Update("value", 0).Error
}
